﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：吕海乐 
    //
    // 文件名：UserList.cs
    // 文件功能描述：主用户管理:主用户列表,多条件查询主用户
    // 创建标识：吕海乐2009-03-10
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;

using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using System.Collections.Generic;
using System.IO;
using HZ.DrugTrade.Model.Enum;

namespace HZ.DrugTrade.Web.Admin
{
    public partial class UserList : BasePage
    {
        IBLL_User iu = Factory.BLL_User();
        public string roleId;
        public UserList()
        {
            this.ModuleNo = Module.系统管理.ToString();
            this.PageOperateType = OperateType.主用户管理.ToString();
        }
        HZ.DrugTrade.BLL.BLL_Log log = new BLL.BLL_Log();
        protected void Page_Load(object sender, EventArgs e)
        {
            //地区招标办登录时 跳转到其专用页面 UserListOfArea.aspx
            IBLL_Area areaCtrl = Factory.BLL_Area();
            Area area = areaCtrl.GetArea(CurrentAccount.GetUser().Org.Area.AreaID);
            if (area.FatherAreaID != "0")
            {
                Response.Redirect("UserListOfArea.aspx");
            }

            if (!IsPostBack)
            {
                this.BindRole();

                SetConditionFromCookie();
                //StoreQureyCondition();
                this.BindUserByOthers();
                IBLL_Hospital hos = Factory.BLL_Hospital();
                this.ddlLevelDetail.DataSource = hos.GetHospitalinfoLevelDetail();
                this.ddlLevelDetail.DataBind();
                this.ddlLevels.DataSource = hos.GetHospitalinfoLevels();
                this.ddlLevels.DataBind();
                                
            }

            //有角色条件限制时方可批量设置权限
            if (this.ddlRoleList.SelectedItem.Value != Constants.ALL_ITEM_VALUE)
            {
                this.btnBatSetOperate.Visible = true;
                if (this.ddlRoleList.Text=="01")
                {
                    this.gvwUser.Columns[5].Visible = true;
                    //this.btnBatSetOperate.Visible = false;
                    this.ddlLevelDetail.Visible = true;
                    this.ddlLevels.Visible = true;
                    this.btnBatSetOperateByHospitalInfo.Visible = true;
                }
                else
                {
                    this.gvwUser.Columns[5].Visible = false;
                    this.ddlLevelDetail.Visible = false;
                    this.ddlLevels.Visible = false;
                    this.btnBatSetOperateByHospitalInfo.Visible = false;
                }
                
            }
            else
            {
                this.gvwUser.Columns[5].Visible = false;
                this.btnBatSetOperate.Visible = false;
                this.ddlLevelDetail.Visible = false;
                this.ddlLevels.Visible = false;
                this.btnBatSetOperateByHospitalInfo.Visible = false;
                
            }
        }



        #region cookie 查询条件相关

        /// <summary>
        /// 
        /// </summary>
        protected void SaveConditionIntoCookie()
        {
            if (IsPostBack)
            {
                setCookie("UserList_txtUserId", this.txtUserId.Text);
                setCookie("UserList_ddlIsUsing", this.ddlIsUsing.SelectedValue);
                setCookie("UserList_ddlRoleList", this.ddlRoleList.SelectedValue);
                setCookie("UserList_txtUserName", this.txtUserName.Text);
                setCookie("UserList_ddlIsOnline", this.ddlIsOnline.SelectedValue);
                setCookie("UserList_txtLoginFrom", this.txtLoginFrom.Text);
                setCookie("UserList_txtLoginTo", this.txtLoginTo.Text);
                setCookie("UserList_CurrentlyPageIndex", AspNetPager1.CurrentPageIndex.ToString());
                setCookie("UserList_CommandArgument", this.lbnSwitch.CommandArgument);
                setCookie("UserList_ddlIslevels", this.ddlLevels.Text);
                setCookie("UserList_ddlIsLevelDetail", this.ddlLevelDetail.Text);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="strValue"></param>
        protected void setCookie(string strName, string strValue)
        {
            HttpCookie cookie = new HttpCookie(strName);
            cookie.Value = HttpUtility.UrlEncode(strValue);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
        /// <summary>
        /// 
        /// </summary>
        protected void SetConditionFromCookie()
        {
            if (!IsPostBack)
            {
                if (HttpContext.Current.Request.Cookies["UserList_txtUserId"] != null)
                    this.txtUserId.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_txtUserId"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_ddlIsUsing"] != null)
                    this.ddlIsUsing.SelectedValue = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_ddlIsUsing"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_ddlRoleList"] != null)
                    this.ddlRoleList.SelectedValue = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_ddlRoleList"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_txtUserName"] != null)
                    this.txtUserName.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_txtUserName"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_ddlIsOnline"] != null)
                    this.ddlIsOnline.SelectedValue = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_ddlIsOnline"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_txtLoginFrom"] != null)
                    this.txtLoginFrom.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_txtLoginFrom"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_txtLoginTo"] != null)
                    this.txtLoginTo.Text = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_txtLoginTo"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_CurrentlyPageIndex"] != null)
                    AspNetPager1.CurrentPageIndex = int.Parse(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_CurrentlyPageIndex"].Value) ?? "1");
                if (HttpContext.Current.Request.Cookies["UserList_CommandArgument"] != null)
                    this.lbnSwitch.CommandArgument = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_CommandArgument"].Value);
                if (HttpContext.Current.Request.Cookies["UserList_ddlIslevels"] != null)
                    this.lbnSwitch.CommandArgument = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_ddlIslevels"].Value);

                //lbnSwitch_Click(new object(), EventArgs.Empty);
            }
        }
        #endregion
        /// <summary>
        /// 绑定所有角色
        /// </summary>
        private void BindRole()
        {
            IBLL_Role ib = Factory.BLL_Role();
            //验证方法是否能被正常调用
            try
            {

                IList<Role> lc = ib.GetAllRole();

                this.ddlRoleList.DataSource = lc;
                this.ddlRoleList.DataTextField = "RoleName";
                this.ddlRoleList.DataValueField = "RoleId";
                this.ddlRoleList.DataBind();
                ListItem item = new ListItem();
                item.Text = Constants.ALL_ITEM_TEXT;
                item.Value = Constants.ALL_ITEM_VALUE;
                ddlRoleList.Items.Insert(0, item);
            }
            catch (Exception ex)
            {
                PageError(ex.Message, "");
            }
        }

        /// <summary>
        /// 根据条件读取用户
        /// </summary>
        private void BindUserByOthers()
        {


            SaveConditionIntoCookie();

            HZ.DrugTrade.Model.Query.OrgUsers user = GetQureyCondition();
            if (user == null)
            {
                StoreQureyCondition();
                user = GetQureyCondition();
            }
            IList<HZ.DrugTrade.Model.View.OrgUsers> lu = new List<HZ.DrugTrade.Model.View.OrgUsers>();
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;

            int TotalCount = 0;

            //验证方法是否能被正常调用
            try
            {
                //if (!IsPostBack)
                //{
                //    if (HttpContext.Current.Request.Cookies["UserList_CurrentlyPageIndex"] != null)
                //        AspNetPager1.CurrentPageIndex = int.Parse(HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies["UserList_CurrentlyPageIndex"].Value) ?? "1");
                //}
                //else
                //{
                //    AspNetPager1.CurrentPageIndex =HZ.MathUtil.SToI(Request["CurrentlyPageIndex"]);          //要显示第几页   
                //}

                lu = iu.GetOrgUsersByWhere(user, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out TotalCount);

                AspNetPager1.RecordCount = TotalCount;
                gvwUser.PageSize = AspNetPager1.PageSize;
                this.gvwUser.DataSource = lu;
                this.gvwUser.DataBind();

            }
            catch (Exception ex)
            {
                PageError(ex.Message, "UserList.aspx");
            }
        }

        /// <summary>
        /// 查询用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            this.gvwUser.EditIndex = -1;
            this.StoreQureyCondition();
            //重置首页
            this.AspNetPager1.CurrentPageIndex = 1;
            //绑定用户列表
            BindUserByOthers();

            //string url = HttpContext.Current.Request.Path;
            //Response.Redirect(HttpContext.Current.Request.Path+"?"+this.AspNetPager1.UrlPageIndexName+"=1&" + Constants.QUERYSTRING_QUERY_CONDITION + "=" + this.QueryCondition);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            this.gvwUser.EditIndex = -1;
            BindUserByOthers();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUserRegister_Click(object sender, EventArgs e)
        {
            HZ.Web.WebUtil.RedirectByScript("UserRegister.aspx");
        }



        /// <summary>
        /// 获取查询条件存入ViewState
        /// </summary>
        /// <returns></returns>
        private HZ.DrugTrade.Model.Query.OrgUsers StoreQureyCondition()
        {
            HZ.DrugTrade.Model.Query.OrgUsers user = new HZ.DrugTrade.Model.Query.OrgUsers();
            user.UserID = this.txtUserId.Text.Trim().ToUpper();
            user.UserName = this.txtUserName.Text.Trim();
            user.RoleID = this.ddlRoleList.SelectedItem.Value;
            
            user.IsAdmin = true;
            if (this.ddlIsUsing.SelectedItem.Value.ToString() == "0")
            {
                user.IsUsing = false;
            }
            else if (this.ddlIsUsing.SelectedItem.Value.ToString() == "1")
            {
                user.IsUsing = true;
            }
            else
            {
                user.IsUsing = null;
            }
            if (this.ddlLevels.Text.Trim() == "-1" || this.ddlLevels.Visible == false)
            {
                user.Levels = null;
            }
            else
            {
                user.Levels = this.ddlLevels.Text.Trim();
            }
            if (this.ddlLevelDetail.Text.Trim() == "-1" || this.ddlLevelDetail.Visible == false)
            {
                user.LevelDetail = null;
            }
            else
            {
                user.LevelDetail = this.ddlLevelDetail.Text.Trim();
            }
            if (this.ddlIsOnline.SelectedItem.Value.ToString() == "0")
            {
                user.IsOnline = false;
            }
            else if (this.ddlIsOnline.SelectedItem.Value.ToString() == "1")
            {
                user.IsOnline = true;
            }
            else
            {
                user.IsOnline = null;
            }
            if (HZ.Common.MyValidate.IsDate(txtLoginFrom.Text.Trim()))
            {
                user.LastlogintimeFrom = Convert.ToDateTime(txtLoginFrom.Text.Trim());
            }
            if (HZ.Common.MyValidate.IsDate(txtLoginTo.Text.Trim()))
            {
                user.LastlogintimeTo = Convert.ToDateTime(txtLoginTo.Text.Trim());
            }
            user.SortFields = "Userid ASC";
            //存储到viewstate
            ViewState[Constants.VIEWSTATE_QUERY_CONDITION] = user;
            //存储到querystring
            //this.SetQueryCondition(user);

            return user;
        }

        /// <summary>
        /// 从ViewState中获取查询条件
        /// </summary>
        private HZ.DrugTrade.Model.Query.OrgUsers GetQureyCondition()
        {
            HZ.DrugTrade.Model.Query.OrgUsers user;

            user = (HZ.DrugTrade.Model.Query.OrgUsers)ViewState[Constants.VIEWSTATE_QUERY_CONDITION];

            return user;
        }


        /// <summary>
        /// 执行锁定和解锁操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "IsUsing")
            {
                string userId = e.CommandArgument.ToString();
                List<string> userIds = new List<string>();
                userIds.Add(userId);
                //批量锁定
                if (iu.LockUser(userIds))
                {
                    //重新加载列表
        
                    this.BindUserByOthers();
                }
                else
                {
                    PageError("锁定/解锁用户失败！", "");
                }
            }
        }

        protected void btnBatLock_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                string strlonth = "";
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    strlonth = strlonth + arryUsers[i] + ",";
                    userIds.Add(arryUsers[i]);
                }

                //批量锁定
                if (iu.LockUser(userIds))
                {
                  
                    BindUserByOthers();
                    //PageInfo("成功锁定选定用户！", "");
                }
                else
                {
                    PageError("锁定用户失败！", "");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatUnLock_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                string strlonth = "";
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    strlonth = strlonth + arryUsers[i] + ",";
                    userIds.Add(arryUsers[i]);
                }

                //批量锁定
                if (iu.UnblockUser(userIds))
                {


                    BindUserByOthers();
                    //PageInfo("成功解锁选定用户！", "");
                }
                else
                {
                    PageError("解锁用户失败！", "");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (Page.IsValid)
            {
                int rowIndex = e.RowIndex;
                string userId = this.gvwUser.DataKeys[rowIndex].Value.ToString();
                string strUserName = ((TextBox)this.gvwUser.Rows[rowIndex].FindControl("txtUserName")).Text.Trim();
                if (string.IsNullOrEmpty(strUserName))
                {
                    HZ.Web.WebUtil.Alert("用户名称不能为空！", this);
                   
                    ((TextBox)gvwUser.Rows[rowIndex].FindControl("txtUserName")).Focus();
                    return;
                }
                User user = new User();
                user.UserID = userId;
                user.UserName = strUserName;
                if (iu.UpdateUser(user) == 1)
                {
                    //重新绑定列表
                  
               
                    this.gvwUser.EditIndex = -1;
                    this.BindUserByOthers();
                }
                else
                {
                    PageError("更新失败！", "");
                }
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.gvwUser.EditIndex = e.NewEditIndex;
            this.BindUserByOthers();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwUser_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.gvwUser.EditIndex = -1;
            this.BindUserByOthers();
        }

        /// <summary>
        /// 初始化密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatResetPws_Click(object sender, EventArgs e)
        {
            string strChkUsers = Request["chkUser"];
            if (!string.IsNullOrEmpty(strChkUsers))
            {
                string[] arryUsers = strChkUsers.Split(new char[',']);
                List<string> userIds = new List<string>();
                string strlonth ="  ";
                for (int i = 0; i < arryUsers.Length; i++)
                {
                    strlonth = strlonth + arryUsers[i];
                    userIds.Add(arryUsers[i]);
                }

                if (iu.InitPassword(userIds, Constants.USER_DEFAULT_PWS))
                {
                  
                    PageInfo("用户" + strChkUsers + "的密码已被初始化为" + Constants.USER_DEFAULT_PWS, "");
                }
                else
                {
                    PageError("密码初始化失败", "");
                }
            }

        }

        /// <summary>
        /// 切换 简单查询
        /// 高级查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lbnSwitch_Click(object sender, EventArgs e)
        {
            if (lbnSwitch.CommandArgument == "simple")
            {
                ltlAdvance.Text = "";
                lbnSwitch.CommandArgument = "advance";
                lbnSwitch.Text = "简单查询";
            }
            else
            {
                ltlAdvance.Text = "<tbody id='advance' style='display:none'>";
                lbnSwitch.CommandArgument = "simple";
                lbnSwitch.Text = "高级查询";

                //清空数据
                //this.txtLoginFrom.Text = "";
                //this.txtLoginTo.Text = "";
                //this.txtUserName.Text = "";
                //this.ddlIsOnline.SelectedIndex = -1;
                //this.ddlIsUsing.SelectedIndex = -1;
                //this.ddlRoleList.SelectedIndex = -1;
            }

        }

        /// <summary>
        /// 批量设置用户权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatSetOperate_Click(object sender, EventArgs e)
        {

            string strChkUsers = Request["chkUser"];
            string strRoleId = this.ddlRoleList.SelectedItem.Value;
            string strRoleName = this.ddlRoleList.SelectedItem.Text;

            if (!string.IsNullOrEmpty(strChkUsers) && !string.IsNullOrEmpty(strRoleId))
            {
                Response.Redirect("UserOperateBatch.aspx?uids=" + strChkUsers + "&rid=" + strRoleId + "&rname=" + HttpUtility.UrlEncode(strRoleName));
            }

        }

        /// <summary>
        /// 批量设置医疗机构的用户权限
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnBatSetOperateByHospitalInfo_Click(object sender, EventArgs e)
        {
            
            
            string strChkUsers=this.ddlLevels.Text+","+this.ddlLevelDetail.Text+"x";
            if (this.ddlLevelDetail.Text == "-1" || this.ddlLevels.Text == "-1")
            {
                this.Page.RegisterStartupScript("", "<script>alert('请选择完整的医疗机构等级!')</script>");
            }
            else
            {
                string strRoleId = this.ddlRoleList.SelectedItem.Value;
                string strRoleName = this.ddlRoleList.SelectedItem.Text;
                if (!string.IsNullOrEmpty(strChkUsers) && !string.IsNullOrEmpty(strRoleId))
                {
                    Response.Redirect("UserOperateBatch.aspx?uids=" + strChkUsers + "&rid=" + strRoleId + "&rname=" + HttpUtility.UrlEncode(strRoleName));
                }
            }
            

        }

        protected void ddllevels_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.gvwUser.EditIndex = -1;
            this.StoreQureyCondition();
            //重置首页
            this.AspNetPager1.CurrentPageIndex = 1;
            //绑定用户列表
            BindUserByOthers();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            SaveConditionIntoCookie();

            HZ.DrugTrade.Model.Query.OrgUsers user = GetQureyCondition();
            if (user == null)
            {
                StoreQureyCondition();
                user = GetQureyCondition();
            }
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.OrgUsers>(user, true);
            string sql = string.Format(@"SELECT Userid 用户编号,UserName 用户名称,case IsUsing when 1 then '启用' when 0 then '禁用' end as 是否启用,
                                        OrgName 用户所属机构 FROM View_OrgUsers WHERE 1=1 {0}", where);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "主用户信息.xls");
        }
    }
}
